﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Collections.Generic;
using System.Security;
using QCCure.Core;
using NLog;
using System.Collections.Specialized;
using System.Media;
using System.Deployment.Application;
using System.IO;

namespace QCCure
{
    public partial class MainForm : Form
    {
        private static Logger log = NLog.LogManager.GetCurrentClassLogger();

        private QCController qc = new QCController();
        private FormLogin loginForm = new FormLogin();
        private FormSettings settingsForm = new FormSettings();
        private FormBugViewer bugViewerForm = new FormBugViewer();
        private FormHelp helpForm = new FormHelp();
        private AboutBox aboutBox = new AboutBox();
        
        private string searchBugIdCache = "0000";

        private Properties.Settings Settings { get { return Properties.Settings.Default; } }
        
        public MainForm()
        {
            InitializeComponent();
            Settings.Reload();
            bugViewer.QC = qc;
            bugViewerForm.BugViewer.QC = qc;
            settingsForm.QC = qc;
            helpForm.AboutBox = aboutBox;

            EnabledFields = false;
        }

        private void buttonGetDefects_Click(object sender, EventArgs e)
        {
            if (!qc.IsConnected)
            {
                MessageBox.Show("Not connected to QC, please make sure the connection is established, and try again");
                return;
            }

            if (buttonGetDefects.Text == "Get &Defects")
            {
                toolStripStatusLabel.Text = "Downloading defects...";
                buttonGetDefects.Text = "Cancel...";
                toolStripSplitButtonConnection.Image = global::QCCure.Properties.Resources.spinner;

                splitContainerBug.Panel2Collapsed = true;

                displayBugBindingSource.Clear();

                backgroundWorkerLoadDefects.RunWorkerAsync();
            }
            else
            {
                backgroundWorkerLoadDefects.CancelAsync();
            }
        }

        private void connectToQCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // if the qcUrl is not set, prompt user to enter the settings.
                if (string.IsNullOrWhiteSpace(Settings.qcUrl))
                {
                    if (settingsForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Login();
                    }
                }
                // if we have the password saved
                else if (Settings.qcLoginName != null && Settings.qcLoginName != "" &&
                    Settings.qcPassword != null && Settings.qcPassword != "")
                {
                    Login();
                } 
                else 
                {
                  
                    loginForm.Username = Settings.qcLoginName;

                    if (Settings.qcPassword != null && Settings.qcPassword != "")
                    {
                        SecureString securePassword = SecureIt.DecryptString(Settings.qcPassword);
                        loginForm.Password = SecureIt.ToInsecureString(securePassword);
                        loginForm.SavePassword = true;
                    }

                    DialogResult result = loginForm.ShowDialog(this);

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        Settings.qcLoginName = loginForm.Username;
                        SecureString securePassword = SecureIt.ToSecureString(loginForm.Password);

                        // clear the password from the textbox so it does not stay in an unsecure state any longer then necessary
                        loginForm.Password = "";

                        // if user has asked to save it, put it in the Settings file encrypted
                        if (loginForm.SavePassword)
                        {
                            // save the password
                            string encryptedPassword = SecureIt.EncryptString(securePassword);
                            Settings.qcPassword = encryptedPassword;
                            Settings.Save();
                        }
                        else
                        {
                            // clear the password
                            Settings.qcPassword = "";
                            Settings.Save();
                        }

                        Login();
                    }
                    else
                    {
                        toolStripStatusLabel.Text = "Not Connected...";
                        EnabledFields = false;
                    }
                }
            }
            catch (Exception ex)
            {
                toolStripStatusLabel.Text = "Failed to connect to: " + Settings.qcUrl;
                MessageBox.Show("Failed to connect to: " + Settings.qcUrl + " due to " + ex.Message);
                EnabledFields = false;
            }
        }

        private void toolStripSplitButtonConnection_ButtonClick(object sender, EventArgs e)
        {
            if (EnabledFields)
            {
                Logout();
            }
            else
            {
                connectToQCToolStripMenuItem_Click(sender, e);
            }
        }

        private void Login()
        {
            toolStripStatusLabel.Text = "Connecting to: " + Settings.qcUrl + "...";
            EnabledFields = false;

            toolStripSplitButtonConnection.Text = "Connecting...";
            toolStripSplitButtonConnection.Image = global::QCCure.Properties.Resources.spinner;

            progressBar.Style = ProgressBarStyle.Marquee;
            progressBar.MarqueeAnimationSpeed = 50;

            backgroundWorkerConnectQC.RunWorkerAsync();
        }

        private void Logout()
        {
            toolStripStatusLabel.Text = "Disconnecting...";

            backgroundWorkerDisconnectQC.RunWorkerAsync();
        }

        private bool EnabledFields
        {
            get
            {
                return buttonGetDefects.Enabled;
            }

            set
            {
                if (value)
                {
                    connectToQCToolStripMenuItem.Text = "&Disconnect";
                }
                else
                {
                    connectToQCToolStripMenuItem.Text = "Connect to &QC...";
                }
                
                buttonGetDefects.Enabled = value;
                
                comboFilterFieldName.Enabled = value;
                textFilterFieldValue.Enabled = value;
                buttonAddFilter.Enabled = value;
                buttonRemoveFilter.Enabled = value;
                
                buttonBugID.Enabled = value;
                buttonMyDefects.Enabled = value;

                filtersToolStripMenuItem.Enabled = value;

                listDefectsToolStripMenuItem.Enabled = value;
                saveFilterAsToolStripMenuItem.Enabled = value;
                filtersToolStripMenuItem.Enabled = value;

                toolStripSplitButtonConnection.Text = (value ? "Connected" : "Disconnected");
                toolStripSplitButtonConnection.Image = (value ? global::QCCure.Properties.Resources.tick : global::QCCure.Properties.Resources.cross);

                if (!value)
                {
                    bugFieldBindingSource.Clear();
                    displayBugBindingSource.Clear();
                    splitContainerBug.Panel2Collapsed = true;

                    LoadHelp(Properties.Resources.HelpLogin);
                }
                else
                {
                    LoadHelp(Properties.Resources.HelpDefectFilter);
                }
            }

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                qc.disconnectFromQC();
                toolStripStatusLabel.Text = "Not Connected...";
                EnabledFields = false;

                helpForm.Terminate = true;
                helpForm.Close();
                bugViewerForm.Terminate = true;
                bugViewerForm.Close();
                aboutBox.Close();
                loginForm.Close();

                Application.Exit();
            }
            catch (QCException ex)
            {
                toolStripStatusLabel.Text = ex.Message;
                log.Warn(ex.Message, ex);
            }
        }
        
        private void backgroundWorkerConnectQC_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker worker = sender as BackgroundWorker;

                log.Debug("starting QCIntegration");

                SecureString securePassword = SecureIt.DecryptString(Settings.qcPassword);
                string unsecurePassword = SecureIt.ToInsecureString(securePassword);

                if (unsecurePassword == "")
                {
                    throw new Exception("Password is required to connect to QC.");
                }

                qc.connectToQC(Settings.qcUrl, Settings.qcDomain, Settings.qcProject, Settings.qcLoginName, unsecurePassword);

                worker.ReportProgress(50, new object[] {
                    "Loading filter list"
                });


                if (qc.IsConnected)
                {
                    QCBugFilter fields = qc.retrieveFilterFields();
                    PopulateFilterList(fields);
                }

                worker.ReportProgress(100, new object[] {
                    "Connected to: " + Settings.qcUrl
                });

            }
            catch (Exception ex)
            {
                BackgroundWorker worker = sender as BackgroundWorker;

                worker.ReportProgress(100, new object[] {
                    "Failed to connect to: " + Settings.qcUrl,
                    "Failed to connect to: " + Settings.qcUrl + " due to " + ex.Message
                });

                if (qc.IsConnected)
                {
                    try
                    {
                        qc.disconnectFromQC();
                    }
                    catch (Exception)
                    {
                        // ingore error here, since we can't do anything at this point
                    }
                }
           }
        }
        
        private void backgroundWorkerConnectQC_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Style = ProgressBarStyle.Marquee;
            progressBar.MarqueeAnimationSpeed = 50;

            if (!(e.UserState is object[]))
            {
                return;
            }

            object[] args = (object[])e.UserState;

            if (args.Length > 0 && args[0] is string)
            {
                string title = (string)args[0];
                toolStripStatusLabel.Text = title;
            }

            if (args.Length > 1 && args[1] is string)
            {
                string errorMessage = (string)args[1];
                MessageBox.Show(errorMessage);
            }
        }


        private void backgroundWorkerConnectQC_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar.Style = ProgressBarStyle.Continuous;
            progressBar.MarqueeAnimationSpeed = 0;

            if (qc.IsConnected)
            {
                EnabledFields = true;
                CreateFilterMenu();
                loadDefaultFilter();
            }
        }

        private void backgroundWorkerLoadDefects_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                QCBugFilter filter = new QCBugFilter();
                foreach (object fieldObj in bugFieldBindingSource.List)
                {
                    QCBugField field = fieldObj as QCBugField;
                    if (field.Name != "")
                    {
                        filter.Add(fieldObj as QCBugField);
                    }
                }

                BackgroundWorker worker = sender as BackgroundWorker;

                worker.ReportProgress(0, new object[] {
                    "Downloading defects for: " + filter
                });

                IList<QCBug> bugs = qc.retrieveBugs(filter);

                worker.ReportProgress(0, new object[] {
                   "Downloaded " + bugs.Count + " defects, loading..."
                });

                int count = 0;
                int total = bugs.Count;
                int currentPercent = 0;

                foreach (QCBug bug in bugs)
                {
                    count++;

                    if (worker.CancellationPending)
                    {
                        worker.ReportProgress(currentPercent, new object[] {
                            "Canceling per user's request at: " + count + " out of " + bugs.Count
                        });

                        break;
                    }

                    AddBugToList(bug);

                    int newPercent = (int)((double)count / (double)total * 100);
                    if (currentPercent != newPercent)
                    {
                        currentPercent = newPercent;

                        worker.ReportProgress(currentPercent, new object[] {
                        "Loading defect: " + count + " out of " + bugs.Count
                    });

                    }
                }

                log.Info("total # of tests updated: " + bugs.Count);
            }
            catch (Exception ex)
            {
                BackgroundWorker worker = sender as BackgroundWorker;

                log.Error("Unable to load defects: ", ex.Message, ex.StackTrace);

                worker.ReportProgress(100, new object[] {
                        "Issue loading defects.", true, "Unable to load defects: " + ex.Message });
            }
        }

        private delegate void PopulateFilterListDelegate(QCBugFilter filterList);
        private void PopulateFilterList(QCBugFilter filterList)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((PopulateFilterListDelegate)PopulateFilterList, new object[] { filterList });
                return;
            }
            
            try {
                comboFilterFieldName.Items.Clear();
                comboFilterFieldName.Items.AddRange(filterList.ToArray<QCBugField>());

                bugViewer.BugFields = filterList;
                bugViewerForm.BugViewer.BugFields = filterList;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to retrive filter list: " + ex.Message);
            }
        }

        private delegate void AddBugToListDelegate(QCBug bug);
        private void AddBugToList(QCBug bug) {
            if (this.InvokeRequired) {
                this.Invoke((AddBugToListDelegate) AddBugToList, new object[] { bug } );
                return;
            }

            displayBugBindingSource.Add(bug);
        }

        private void backgroundWorkerLoadDefects_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Style = ProgressBarStyle.Continuous;
            progressBar.Value = e.ProgressPercentage;
            
            if (e.ProgressPercentage == 100)
            {
                toolStripStatusLabel.Text = "All defects loaded";
            }

            if (!(e.UserState is object[]))
            {
                return;
            }

            object[] args = (object[])e.UserState;

            if (args.Length > 0 && args[0] is string)
            {
                string title = (string)args[0];
                toolStripStatusLabel.Text = title;
            }

            if (args.Length > 1 && args[1] is bool)
            {
                bool enableGetDefects = (bool)args[1];
                if (enableGetDefects)
                {
                    buttonGetDefects.Text = "Get &Defects";
                }
                else
                {
                    buttonGetDefects.Text = "Cancel...";
                }
            }

            if (args.Length > 2 && args[2] is string)
            {
                string errorMessage = (string)args[2];
                MessageBox.Show(errorMessage);
            }
        }

        private void backgroundWorkerLoadDefects_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.buttonGetDefects.Enabled = true;
            this.buttonGetDefects.Text = "Get &Defects";
            toolStripSplitButtonConnection.Image = global::QCCure.Properties.Resources.tick;

            if (displayBugBindingSource.Count == 0)
            {
                splitContainerBug.Panel2Collapsed = true;
            }
            else
            {
                if (previewDefectsToolStripMenuItem.Checked)
                {
                    splitContainerBug.Panel2Collapsed = false;
                }
            }

            LoadHelp(Properties.Resources.HelpViewingDefect);
        }
        
        private void backgroundWorkerDisconnectQC_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                qc.disconnectFromQC();
            }
            catch (QCException ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void backgroundWorkerDisconnectQC_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripStatusLabel.Text = "Not Connected...";

            EnabledFields = false;
        }

        private void buttonClearFilter_Click(object sender, EventArgs e)
        {
            bugFieldBindingSource.Clear();
        }

        private void buttonAddFilter_Click(object sender, EventArgs e)
        {
            AddToFilter();
        }

        private void buttonRemoveFilter_Click(object sender, EventArgs e)
        {
            List<QCBugField> fieldsToRemove = new List<QCBugField>();

            foreach (DataGridViewRow row in listFilter.SelectedRows)
            {
                try
                {
                    QCBugField field = row.DataBoundItem as QCBugField;
                    if (field != null)
                    {
                        fieldsToRemove.Add(field);
                    }
                }
                catch (Exception ex)
                {
                    // since the control may select the out of bound row, ignore it.
                    log.Warn(ex);
                }
            }

            foreach (QCBugField field in fieldsToRemove) {
                bugFieldBindingSource.Remove(field);
            }
        }

        private void textFilterFieldValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddToFilter();
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            aboutBox.ShowDialog(this);            
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            settingsForm.ShowDialog();
        }

        private void listFilter_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            foreach (DataGridViewRow row in listFilter.SelectedRows)
            {
                try
                {
                    QCBugField field = row.DataBoundItem as QCBugField;
                    if (field != null)
                    {
                        comboFilterFieldName.SelectedItem = field;
                        textFilterFieldValue.Text = field.Value;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    // since the control may select the out of bound row, ignore it.
                    log.Warn(ex);
                }
            }
        }

        private void listBugs_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (previewDefectsToolStripMenuItem.Checked)
                {
                    foreach (DataGridViewRow row in listBugs.SelectedRows)
                    {
                        QCBug bug = row.DataBoundItem as QCBug;
                        if (bug != null)
                        {
                            bugViewer.Bug = bug;
                            splitContainerBug.Panel2Collapsed = false;
                            return;
                        }
                    }

                    bugViewer.Bug = null;
                    splitContainerBug.Panel2Collapsed = true;
                }
            }
            catch (Exception ex)
            {
                // Ignore any errors here
                log.Warn(ex);
            }
        }


        private void listBugs_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in listBugs.SelectedRows)
                {
                    QCBug bug = row.DataBoundItem as QCBug;
                    if (bug != null)
                    {
                        bugViewerForm.BugViewer.Bug = bug;
                        splitContainerBug.Panel2Collapsed = true;
                        
                        bugViewerForm.Show(this);
                        return;
                    }
                }

                bugViewerForm.BugViewer.Bug = null;
            }
            catch (Exception ex)
            {
                // Ignore any errors here
                log.Warn(ex);
            }
        }


        private void loadFilter(string filterString)
        {
            QCBugFilter filter = new QCBugFilter(filterString, qc);

            foreach (object item in comboFilterFieldName.Items)
            {
                filter.Add(item as QCBugField);
            }

            loadFilter(filter);
        }


        private void clearFilter()
        {
            bugFieldBindingSource.Clear();
        }


        private void loadFilter(QCBugFilter filter)
        {
            bugFieldBindingSource.Clear();
            foreach (QCBugField field in filter)
            {
                if (field.Value != null)
                {
                    bugFieldBindingSource.Add(field);
                }
            }
        }

        private void comboFilterFieldName_SelectedIndexChanged(object sender, EventArgs e)
        {
            textFilterFieldValue.Items.Clear();
            if (string.Equals("Responsible".ToUpper(), comboFilterFieldName.Text.ToUpper()))
            {
                textFilterFieldValue.Items.AddRange(qc.retrieveUsers().ToArray());
                textFilterFieldValue.Items.AddRange(qc.retrieveUserGroups().ToArray());
            }
            else if (string.Equals("Status".ToUpper(), comboFilterFieldName.Text.ToUpper()))
            {
                textFilterFieldValue.Items.AddRange(qc.retrieveStatusList().ToArray());
            }
            
        }

        private void textFilterFieldValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            AddToFilter();
        }

        private void AddToFilter()
        {
            object item = comboFilterFieldName.SelectedItem;

            if (item != null)
            {
                QCBugField field = item as QCBugField;

                string value = textFilterFieldValue.Text;

                // try to auto-complete
                // if user has extered text, nothing is selected, and the field has a list of values 
                if (!string.IsNullOrWhiteSpace(value) 
                    && textFilterFieldValue.SelectedItem == null 
                    && textFilterFieldValue.Items.Count > 0)
                {
                    // Look for the value that starts with the text entered 
                    foreach (object valueItem in textFilterFieldValue.Items)
                    {
                        if (item != null && item.ToString().StartsWith(comboFilterFieldName.Text, StringComparison.CurrentCultureIgnoreCase))
                        {
                            textFilterFieldValue.SelectedItem = item;
                            break;
                        }
                    }
                }

                object obj = textFilterFieldValue.SelectedItem;

                if (obj != null && obj is QCUser && obj.ToString().Equals(value))
                {
                    QCUser user = obj as QCUser;

                    field.Value = user.Username;
                }
                else if (obj != null && obj is QCUserGroup && obj.ToString().Equals(value))
                {
                    QCUserGroup userGroup = obj as QCUserGroup;

                    field.Value = userGroup.Name;
                }
                else
                {
                    field.Value = value;
                }

                if (bugFieldBindingSource.Contains(field))
                {
                    bugFieldBindingSource.Remove(field);
                }

                bugFieldBindingSource.Add(field);
            }
        }
        
        private void loadDefaultFilter()
        {
            try
            {
                // load the first filter

                if (Settings.qcFilters != null && Settings.qcFilters.Count > 0)
                {
                    loadFilter(Settings.qcFilters[0]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to retrive filter list: " + ex.Message);
            }
        }

        private void saveFilterAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IList<QCBugField> fields = bugFieldBindingSource.List as IList<QCBugField>;

                string filterName = FormPrompt.Show("Please enter the name of the filter", "Enter Name", "[Custom Filter]");
                if (string.IsNullOrWhiteSpace(filterName))
                {
                    return;
                }

                // since this 
                QCBugFilter filter = new QCBugFilter(filterName, fields);

                //string filterString = filter.ToStorableString(qc);

                if (Settings.qcFilters == null)
                {
                    Settings.qcFilters = new QCBugFilterList();
                }

                Settings.qcFilters.Add(filter);
                Settings.Save();

                CreateFilterMenu();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to retrive filter list: " + ex.Message);
            }
        }
        
        private void CreateFilterMenu()
        {
            this.filtersToolStripMenuItem.DropDownItems.Clear();

            QCBugFilterList filterList = Settings.qcFilters;
            if (filterList != null)
            {
                foreach (QCBugFilter filter in filterList)
                {
                    ToolStripMenuItem filterMenuItem = new ToolStripMenuItem();
                    filterMenuItem.Size = new System.Drawing.Size(152, 22);
                    filterMenuItem.Text = filter.Name;
                    filterMenuItem.Click += new EventHandler(filterMenuItem_Click);
                    filterMenuItem.Tag = filter;

                    this.filtersToolStripMenuItem.DropDownItems.Add(filterMenuItem);
                }
            }

            if (this.filtersToolStripMenuItem.DropDownItems.Count == 0)
            {
                this.filtersToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem("No Filters Saved."));
            }
        }

        void filterMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem filterMenuItem = sender as ToolStripMenuItem;
            if (filterMenuItem.Tag != null && filterMenuItem.Tag is QCBugFilter)
            {
                QCBugFilter filter = filterMenuItem.Tag as QCBugFilter;
                loadFilter(filter);
            }
            else
            {
                MessageBox.Show("Invalid filter");
            }
        }

        private void helpToolStripMenuItemHelp_Click(object sender, EventArgs e)
        {
            helpForm.Show(this);
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            splitContainerBug.Panel2Collapsed = true;
            splitContainerTotal.Panel2Collapsed = false;
            LoadHelp(Properties.Resources.HelpLogin);
        }

        private void listDefectsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            buttonGetDefects_Click(sender, e);
        }
        
        private void previewDefectsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            splitContainerBug.Panel2Collapsed = !previewDefectsToolStripMenuItem.Checked;
        }

        private void comboFilterFieldName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (validateFilterFieldName()) 
                {
                    textFilterFieldValue.Focus();
                }
            }
        }

        private void comboFilterFieldName_Leave(object sender, EventArgs e)
        {
            validateFilterFieldName();
        }

        private bool validateFilterFieldName()
        {
            // if the user just typed in something, but did not select it
            if (!String.IsNullOrWhiteSpace(comboFilterFieldName.Text) &&
                comboFilterFieldName.SelectedItem == null)
            {
                foreach (object item in comboFilterFieldName.Items)
                {
                    if (item != null && item.ToString().StartsWith(comboFilterFieldName.Text, StringComparison.CurrentCultureIgnoreCase))
                    {
                        comboFilterFieldName.SelectedItem = item;
                        break;
                    }
                }
            }

            if (comboFilterFieldName.SelectedItem == null)
            {
                SystemSounds.Hand.Play();
                return false;
            }
            
            return true;
        }

        private void toolStripDropDownButtonHelp_Click(object sender, EventArgs e)
        {
            splitContainerTotal.Panel2Collapsed = !splitContainerTotal.Panel2Collapsed;
        }

        private void toolStripMenuShowHelpBar_Click(object sender, EventArgs e)
        {
            splitContainerTotal.Panel2Collapsed = !toolStripMenuShowHelpBar.Checked;
        }

        private void LoadHelp(string helpContent)
        {
            try
            {
                string contents = helpForm.RepalceHelpText(helpContent);

                editorHelp.DocumentText = contents;
            }
            catch (Exception ex)
            {
                editorHelp.DocumentText = "Unable to load help information: " + ex.Message;
            }
        }

        private void addFieldToFilter(string name, string value)
        {
            foreach (object item in comboFilterFieldName.Items) {
                QCBugField field = item as QCBugField;
                if (name.Equals(field.Name))
                {
                    field.Value = value;

                    bugFieldBindingSource.Add(field);
                }
            }
        }

        private void addFieldToFilter(QCBugField field)
        {
            bugFieldBindingSource.Add(field);
        }

        private void buttonBugID_Click(object sender, EventArgs e)
        {
            try
            {
                string bugId = FormPrompt.Show("Please enter the Bug ID", "Enter BUG ID", searchBugIdCache);
                int bugIdInt = 0;

                if (bugId != null)
                {
                    bugId = bugId.Trim();

                    if (!int.TryParse(bugId, out bugIdInt))
                    {
                        MessageBox.Show(this, "Invalid Bug ID: " + bugId, "Invalid Bug ID.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        searchBugIdCache = bugId;

                        clearFilter();
                        addFieldToFilter("BUG_ID", bugId);
                        buttonGetDefects_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Unable to run the filter: " + ex.Message, "System Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonMyDefects_Click(object sender, EventArgs e)
        {
            try
            {
                clearFilter();
                addFieldToFilter("STATUS", "Not Closed");
                addFieldToFilter("RESPONSIBLE", qc.LoggedinUser.Username);
                buttonGetDefects_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Unable to run the filter: " + ex.Message, "System Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
